/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojo.Category;
import pojo.Food;
import pojo.Ingredient;
import java.util.ArrayList;
import java.util.Collection;
import pojo.Coupons;
import pojo.Orderdetail;

/**
 *
 * @author A7med Kotb
 */
public class FoodJpaController implements Serializable {

    public FoodJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Food food) throws RollbackFailureException, Exception {
        if (food.getIngredientCollection() == null) {
            food.setIngredientCollection(new ArrayList<Ingredient>());
        }
        if (food.getCouponsCollection() == null) {
            food.setCouponsCollection(new ArrayList<Coupons>());
        }
        if (food.getOrderdetailCollection() == null) {
            food.setOrderdetailCollection(new ArrayList<Orderdetail>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Category categoryId = food.getCategoryId();
            if (categoryId != null) {
                categoryId = em.getReference(categoryId.getClass(), categoryId.getId());
                food.setCategoryId(categoryId);
            }
            Collection<Ingredient> attachedIngredientCollection = new ArrayList<Ingredient>();
            for (Ingredient ingredientCollectionIngredientToAttach : food.getIngredientCollection()) {
                ingredientCollectionIngredientToAttach = em.getReference(ingredientCollectionIngredientToAttach.getClass(), ingredientCollectionIngredientToAttach.getId());
                attachedIngredientCollection.add(ingredientCollectionIngredientToAttach);
            }
            food.setIngredientCollection(attachedIngredientCollection);
            Collection<Coupons> attachedCouponsCollection = new ArrayList<Coupons>();
            for (Coupons couponsCollectionCouponsToAttach : food.getCouponsCollection()) {
                couponsCollectionCouponsToAttach = em.getReference(couponsCollectionCouponsToAttach.getClass(), couponsCollectionCouponsToAttach.getCId());
                attachedCouponsCollection.add(couponsCollectionCouponsToAttach);
            }
            food.setCouponsCollection(attachedCouponsCollection);
            Collection<Orderdetail> attachedOrderdetailCollection = new ArrayList<Orderdetail>();
            for (Orderdetail orderdetailCollectionOrderdetailToAttach : food.getOrderdetailCollection()) {
                orderdetailCollectionOrderdetailToAttach = em.getReference(orderdetailCollectionOrderdetailToAttach.getClass(), orderdetailCollectionOrderdetailToAttach.getId());
                attachedOrderdetailCollection.add(orderdetailCollectionOrderdetailToAttach);
            }
            food.setOrderdetailCollection(attachedOrderdetailCollection);
            em.persist(food);
            if (categoryId != null) {
                categoryId.getFoodCollection().add(food);
                categoryId = em.merge(categoryId);
            }
            for (Ingredient ingredientCollectionIngredient : food.getIngredientCollection()) {
                ingredientCollectionIngredient.getFoodCollection().add(food);
                ingredientCollectionIngredient = em.merge(ingredientCollectionIngredient);
            }
            for (Coupons couponsCollectionCoupons : food.getCouponsCollection()) {
                Food oldFoodIdOfCouponsCollectionCoupons = couponsCollectionCoupons.getFoodId();
                couponsCollectionCoupons.setFoodId(food);
                couponsCollectionCoupons = em.merge(couponsCollectionCoupons);
                if (oldFoodIdOfCouponsCollectionCoupons != null) {
                    oldFoodIdOfCouponsCollectionCoupons.getCouponsCollection().remove(couponsCollectionCoupons);
                    oldFoodIdOfCouponsCollectionCoupons = em.merge(oldFoodIdOfCouponsCollectionCoupons);
                }
            }
            for (Orderdetail orderdetailCollectionOrderdetail : food.getOrderdetailCollection()) {
                Food oldFoodIdOfOrderdetailCollectionOrderdetail = orderdetailCollectionOrderdetail.getFoodId();
                orderdetailCollectionOrderdetail.setFoodId(food);
                orderdetailCollectionOrderdetail = em.merge(orderdetailCollectionOrderdetail);
                if (oldFoodIdOfOrderdetailCollectionOrderdetail != null) {
                    oldFoodIdOfOrderdetailCollectionOrderdetail.getOrderdetailCollection().remove(orderdetailCollectionOrderdetail);
                    oldFoodIdOfOrderdetailCollectionOrderdetail = em.merge(oldFoodIdOfOrderdetailCollectionOrderdetail);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Food food) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Food persistentFood = em.find(Food.class, food.getId());
            Category categoryIdOld = persistentFood.getCategoryId();
            Category categoryIdNew = food.getCategoryId();
            Collection<Ingredient> ingredientCollectionOld = persistentFood.getIngredientCollection();
            Collection<Ingredient> ingredientCollectionNew = food.getIngredientCollection();
            Collection<Coupons> couponsCollectionOld = persistentFood.getCouponsCollection();
            Collection<Coupons> couponsCollectionNew = food.getCouponsCollection();
            Collection<Orderdetail> orderdetailCollectionOld = persistentFood.getOrderdetailCollection();
            Collection<Orderdetail> orderdetailCollectionNew = food.getOrderdetailCollection();
            List<String> illegalOrphanMessages = null;
            for (Orderdetail orderdetailCollectionOldOrderdetail : orderdetailCollectionOld) {
                if (!orderdetailCollectionNew.contains(orderdetailCollectionOldOrderdetail)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Orderdetail " + orderdetailCollectionOldOrderdetail + " since its foodId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (categoryIdNew != null) {
                categoryIdNew = em.getReference(categoryIdNew.getClass(), categoryIdNew.getId());
                food.setCategoryId(categoryIdNew);
            }
            Collection<Ingredient> attachedIngredientCollectionNew = new ArrayList<Ingredient>();
            for (Ingredient ingredientCollectionNewIngredientToAttach : ingredientCollectionNew) {
                ingredientCollectionNewIngredientToAttach = em.getReference(ingredientCollectionNewIngredientToAttach.getClass(), ingredientCollectionNewIngredientToAttach.getId());
                attachedIngredientCollectionNew.add(ingredientCollectionNewIngredientToAttach);
            }
            ingredientCollectionNew = attachedIngredientCollectionNew;
            food.setIngredientCollection(ingredientCollectionNew);
            Collection<Coupons> attachedCouponsCollectionNew = new ArrayList<Coupons>();
            for (Coupons couponsCollectionNewCouponsToAttach : couponsCollectionNew) {
                couponsCollectionNewCouponsToAttach = em.getReference(couponsCollectionNewCouponsToAttach.getClass(), couponsCollectionNewCouponsToAttach.getCId());
                attachedCouponsCollectionNew.add(couponsCollectionNewCouponsToAttach);
            }
            couponsCollectionNew = attachedCouponsCollectionNew;
            food.setCouponsCollection(couponsCollectionNew);
            Collection<Orderdetail> attachedOrderdetailCollectionNew = new ArrayList<Orderdetail>();
            for (Orderdetail orderdetailCollectionNewOrderdetailToAttach : orderdetailCollectionNew) {
                orderdetailCollectionNewOrderdetailToAttach = em.getReference(orderdetailCollectionNewOrderdetailToAttach.getClass(), orderdetailCollectionNewOrderdetailToAttach.getId());
                attachedOrderdetailCollectionNew.add(orderdetailCollectionNewOrderdetailToAttach);
            }
            orderdetailCollectionNew = attachedOrderdetailCollectionNew;
            food.setOrderdetailCollection(orderdetailCollectionNew);
            food = em.merge(food);
            if (categoryIdOld != null && !categoryIdOld.equals(categoryIdNew)) {
                categoryIdOld.getFoodCollection().remove(food);
                categoryIdOld = em.merge(categoryIdOld);
            }
            if (categoryIdNew != null && !categoryIdNew.equals(categoryIdOld)) {
                categoryIdNew.getFoodCollection().add(food);
                categoryIdNew = em.merge(categoryIdNew);
            }
            for (Ingredient ingredientCollectionOldIngredient : ingredientCollectionOld) {
                if (!ingredientCollectionNew.contains(ingredientCollectionOldIngredient)) {
                    ingredientCollectionOldIngredient.getFoodCollection().remove(food);
                    ingredientCollectionOldIngredient = em.merge(ingredientCollectionOldIngredient);
                }
            }
            for (Ingredient ingredientCollectionNewIngredient : ingredientCollectionNew) {
                if (!ingredientCollectionOld.contains(ingredientCollectionNewIngredient)) {
                    ingredientCollectionNewIngredient.getFoodCollection().add(food);
                    ingredientCollectionNewIngredient = em.merge(ingredientCollectionNewIngredient);
                }
            }
            for (Coupons couponsCollectionOldCoupons : couponsCollectionOld) {
                if (!couponsCollectionNew.contains(couponsCollectionOldCoupons)) {
                    couponsCollectionOldCoupons.setFoodId(null);
                    couponsCollectionOldCoupons = em.merge(couponsCollectionOldCoupons);
                }
            }
            for (Coupons couponsCollectionNewCoupons : couponsCollectionNew) {
                if (!couponsCollectionOld.contains(couponsCollectionNewCoupons)) {
                    Food oldFoodIdOfCouponsCollectionNewCoupons = couponsCollectionNewCoupons.getFoodId();
                    couponsCollectionNewCoupons.setFoodId(food);
                    couponsCollectionNewCoupons = em.merge(couponsCollectionNewCoupons);
                    if (oldFoodIdOfCouponsCollectionNewCoupons != null && !oldFoodIdOfCouponsCollectionNewCoupons.equals(food)) {
                        oldFoodIdOfCouponsCollectionNewCoupons.getCouponsCollection().remove(couponsCollectionNewCoupons);
                        oldFoodIdOfCouponsCollectionNewCoupons = em.merge(oldFoodIdOfCouponsCollectionNewCoupons);
                    }
                }
            }
            for (Orderdetail orderdetailCollectionNewOrderdetail : orderdetailCollectionNew) {
                if (!orderdetailCollectionOld.contains(orderdetailCollectionNewOrderdetail)) {
                    Food oldFoodIdOfOrderdetailCollectionNewOrderdetail = orderdetailCollectionNewOrderdetail.getFoodId();
                    orderdetailCollectionNewOrderdetail.setFoodId(food);
                    orderdetailCollectionNewOrderdetail = em.merge(orderdetailCollectionNewOrderdetail);
                    if (oldFoodIdOfOrderdetailCollectionNewOrderdetail != null && !oldFoodIdOfOrderdetailCollectionNewOrderdetail.equals(food)) {
                        oldFoodIdOfOrderdetailCollectionNewOrderdetail.getOrderdetailCollection().remove(orderdetailCollectionNewOrderdetail);
                        oldFoodIdOfOrderdetailCollectionNewOrderdetail = em.merge(oldFoodIdOfOrderdetailCollectionNewOrderdetail);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = food.getId();
                if (findFood(id) == null) {
                    throw new NonexistentEntityException("The food with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Food food;
            try {
                food = em.getReference(Food.class, id);
                food.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The food with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Orderdetail> orderdetailCollectionOrphanCheck = food.getOrderdetailCollection();
            for (Orderdetail orderdetailCollectionOrphanCheckOrderdetail : orderdetailCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Food (" + food + ") cannot be destroyed since the Orderdetail " + orderdetailCollectionOrphanCheckOrderdetail + " in its orderdetailCollection field has a non-nullable foodId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Category categoryId = food.getCategoryId();
            if (categoryId != null) {
                categoryId.getFoodCollection().remove(food);
                categoryId = em.merge(categoryId);
            }
            Collection<Ingredient> ingredientCollection = food.getIngredientCollection();
            for (Ingredient ingredientCollectionIngredient : ingredientCollection) {
                ingredientCollectionIngredient.getFoodCollection().remove(food);
                ingredientCollectionIngredient = em.merge(ingredientCollectionIngredient);
            }
            Collection<Coupons> couponsCollection = food.getCouponsCollection();
            for (Coupons couponsCollectionCoupons : couponsCollection) {
                couponsCollectionCoupons.setFoodId(null);
                couponsCollectionCoupons = em.merge(couponsCollectionCoupons);
            }
            em.remove(food);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Food> findFoodEntities() {
        return findFoodEntities(true, -1, -1);
    }

    public List<Food> findFoodEntities(int maxResults, int firstResult) {
        return findFoodEntities(false, maxResults, firstResult);
    }

    private List<Food> findFoodEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Food.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Food findFood(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Food.class, id);
        } finally {
            em.close();
        }
    }

    public int getFoodCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Food> rt = cq.from(Food.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
